package com.ken.common.event.core.rabbitmq.core;

import com.ken.common.event.apply.delay.DelayTime;
import com.ken.common.event.core.rabbitmq.constact.RabbitMqConstact;
import com.ken.common.event.framework.message.EventMessage;
import com.ken.common.event.framework.producer.ProducerStandard;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * rabbitmq实现的提供者
 */
public class RabbitMQProducerStandard implements ProducerStandard {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 发送消息
     * @param eventType
     * @param message 消息内容
     * @param durable 是否持久化
     */
    @Override
    public void sendEvent(String eventType, EventMessage message, boolean durable) {
        //消息转换 Object -> byte[]
        byte[] body = SerializationUtils.serialize(message);

        //将消息封装成消息对象
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setDeliveryMode(durable ? MessageDeliveryMode.PERSISTENT : MessageDeliveryMode.NON_PERSISTENT);
        Message msg = new Message(body, messageProperties);

        //发布事件
        rabbitTemplate.send(RabbitMqConstact.EVENT_EXCHANGE, eventType, msg);
    }

    /**
     * 发送延迟消息
     * @param eventType
     * @param message
     * @param durable
     * @param delayTime
     */
    @Override
    public void sendDelayEvent(String eventType, EventMessage message, boolean durable, DelayTime delayTime) {
        //消息转换 Object -> byte[]
        byte[] body = SerializationUtils.serialize(message);

        //将消息封装成消息对象
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setDeliveryMode(durable ? MessageDeliveryMode.PERSISTENT : MessageDeliveryMode.NON_PERSISTENT);
        Message msg = new Message(body, messageProperties);

        //发布延迟消息
        rabbitTemplate.send(RabbitMqConstact.EVENT_EXCHANGE_DELAY, eventType + "." + delayTime.getName(), msg);
    }
}
